const PENDDING = 'pendding'
const FULLFILLED = 'fullfilled'
const REJECTED = 'rejected'


class MyPromise {
  status = PENDDING
  value = null
  reason = null
  onFullfilled = []
  onRejected = []
  constructor(exec) {
    exec(this.resolve, this.reject)
  }
  resolve = (value) => {
    if (this.status === PENDDING) {
      this.status = FULLFILLED
      this.value = value
      while (this.onFullfilled.length > 0) {
        this.onFullfilled.shift()(value)
      }
    }
  }
  reject = (reason) => {
    if (this.status === PENDDING) {
      this.status = REJECTED
      this.reason = reason
      while (this.onRejected.length > 0) {
        this.onRejected.shift()(value)
      }
    }
  }
  then(onFullfilled, onRejected) {
    return new MyPromise((resolve, reject) => {
      if (this.status === PENDDING) {
        this.onFullfilled.push(onFullfilled)
        this.onRejected.push(onRejected)
      } else if (this.status === FULLFILLED) {
        const x = onFullfilled(this.value)
        // 判断resolve返回的是否为promise对象，如果是则.then执行掉
        resolvePromise(x, resolve, reject)
      } else if (this.status === REJECTED) {
        onRejected(this.reason)
      }

    })
  }
}


function resolvePromise(x, resolve, reject) {
  if (x instanceof MyPromise) {
    x.then(resolve, reject)
  } else {
    resolve(x)
  }
}